package com.demo.dao.impl;

import com.demo.dao.CustomerDao;
import com.demo.dao.DepartMentDao;
import com.demo.domain.Customer;
import com.demo.domain.Department;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.ArrayList;
import java.util.List;

public class DepartMentDaoImpl extends HibernateDaoSupport implements DepartMentDao {

    @Override
    public void addDepartMent(Department department) {

        getHibernateTemplate().save(department);
    }

    @Override
    public List<Department> find() {
        List<Department> list = (List<Department>) getHibernateTemplate().find("from Department ");
        return list;
    }

    @Override
    //拿到id
    public Department findOne(long d_id) {
        return getHibernateTemplate().get(Department.class, d_id);
    }

    @Override
    public void delete(Department d) {

    }

    @Override
    public void update(Department department) {

    }

    @Override
    public List<Department> findMoreCondition(Department department) {
//        List<Object> p = new ArrayList<Object>();
//        // 拼接hql语句
//        String hql = "from Department where 1=1"; // where一个肯定成立的条件
//        if (department.getD_name()!= null && !"".equals(department.getD_name())) {
//            hql += " and d_name=?";
//            p.add(department.getD_name());
//        }
//        if (department.getCustomer().getCust_id() != null
//                && department.getCustomer().getCust_id() > 0) {
//            hql += " and customer.cust_id=?";
//            p.add(department.getCustomer().getCust_id() );
//        }
//
//        List<Department> list = (List<Department>) this.getHibernateTemplate().find(
//                hql, p.toArray());
//        return list;
        //创建离线对象，指定对哪个实体类进行操作
        DetachedCriteria criteria = DetachedCriteria.forClass(Department.class);
        // 判断条件值是否为空
        if (department.getD_name() != null && !"".equals(department.getD_name())) {
            // 设置对属性，设置值
            criteria.add(Restrictions.eq("d_name", department.getD_name()));
        }
        if (department.getCustomer().getCust_id() != null
                && department.getCustomer().getCust_id() > 0) {
            criteria.add(Restrictions.eq("customer.cust_id", department.getCustomer()
                    .getCust_id()));
        }

        return (List<Department>) this.getHibernateTemplate().findByCriteria(
                criteria);
    }
}
